package com.sch.wanandroid.ui.main.discover.system.list

import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.coder.zzq.smartshow.toast.SmartToast
import com.sch.wanandroid.R
import com.sch.wanandroid.adapter.ArticleAdapter
import com.sch.wanandroid.base.BaseActivity
import com.sch.wanandroid.constants.Constants
import com.sch.wanandroid.entity.ArticleBean
import com.sch.wanandroid.ui.web.WebActivity
import com.sch.wanandroid.util.AppManager
import kotlinx.android.synthetic.main.activity_system_list.*
import kotlinx.android.synthetic.main.activity_system_list.loadingTip

/**
 * Created by Sch.
 * Date: 2020/4/23
 * description:
 */
class SystemListActivity : BaseActivity() {
    private lateinit var systemListViewModel: SystemListViewModel
    private var title: String=""
    private var cid: Int = 0
    private val articleAdapter by lazy { ArticleAdapter() }
    private var pageNum = 0
    val articleList by lazy { mutableListOf<ArticleBean>() }

    private var collectPosition = 0

    /**
     * 点击收藏后将点击事件上锁,等接口有相应结果再解锁
     * 避免重复点击产生的bug  false表示没锁，true表示锁住
     */
    private var lockCollectClick = false

    override fun init(savedInstanceState: Bundle?) {
        systemListViewModel = ViewModelProvider(this).get(SystemListViewModel::class.java)

        val bundle: Bundle? = intent.extras
        cid = bundle?.getInt(Constants.SYSTEM_ID)!!
        title = bundle?.getString(Constants.SYSTEM_TITLE)!!
        initTitle(title)

        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = articleAdapter
        recyclerView.overScrollMode = RecyclerView.OVER_SCROLL_NEVER//取消滑动到顶部边界越界效果
        initListener()
//加载中动画
        loadingTip.loading()
        loadData()
        systemListViewModel.articleListLiveData.observe(this, Observer {
            setData(it)
        })
        systemListViewModel.errorMsg.observe(this) {
            onError(it)
        }
        systemListViewModel.collectSuccess.observe(this) {
            if (it) {
                collectSuccess()
            }
        }
        systemListViewModel.uncollectSuccess.observe(this) {
            if (it) {
                unCollectSuccess()
            }
        }
    }

    private fun loadData() {
        articleList.clear()
        articleAdapter.setList(articleList)
        pageNum = 0
        systemListViewModel.getArticleData(pageNum, cid)
    }

    private fun setData(list: List<ArticleBean>) {
        dismissRefresh()
        if (list.isNotEmpty()) {
            articleList.addAll(list)
            articleAdapter.setList(articleList)
        } else {
            if (articleList.size == 0) loadingTip.showEmpty()
            else SmartToast.info("没有更多数据了")
        }
    }

    private fun initListener() {
        articleAdapter.setOnItemClickListener { adapter, view, position ->
            intent(Bundle().apply {
                putString(Constants.WEB_URL, articleList[position].link)
                putString(Constants.WEB_TITLE, articleList[position].title)
            }, WebActivity::class.java, false)
        }
        articleAdapter.addChildClickViewIds(R.id.ivCollect)
        articleAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.ivCollect) {
                if (!AppManager.isLogin()) {
                    SmartToast.show("请先登录")
                    return@setOnItemChildClickListener
                }
                if (position < articleList.size && !lockCollectClick) {
                    lockCollectClick = true
                    collectPosition = position
                    articleList[position].apply {
                        if (collect) {
                            systemListViewModel.unCollect(id)
                        } else {
                            systemListViewModel.collect(id)
                        }
                    }
                }
            }
        }
        // 设置无网络时重新加载点击事件
        loadingTip.setReloadListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                loadingTip.loading()
                loadData()
            }
        })
        //下拉监听
        smartRefresh.setOnRefreshListener {
            loadData()
        }
        smartRefresh.setOnLoadMoreListener {
            pageNum++
            systemListViewModel.getArticleData(pageNum, cid)
        }
        articleAdapter.setOnItemClickListener { adapter, view, position ->
            intent(Bundle().apply {
                putString(Constants.WEB_URL, articleList[position].link)
                putString(Constants.WEB_TITLE, articleList[position].title)
            }, WebActivity::class.java, false)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_system_list
    }


    fun onError(ex: String?) {
        lockCollectClick = false
        //请求失败将page -1
        if (pageNum > 0) pageNum--
        dismissRefresh()
        if (articleList.size == 0) {
            loadingTip.showInternetError()
        }
        SmartToast.error(ex)
    }

    fun collectSuccess() {
        lockCollectClick = false
        if (collectPosition < articleList.size) {
            articleList[collectPosition].collect = true
            articleAdapter.setList(articleList)
        }
    }

    fun unCollectSuccess() {
        lockCollectClick = false
        if (collectPosition < articleList.size) {
            articleList[collectPosition].collect = false
            articleAdapter.setList(articleList)
        }
    }

    /**
     * 隐藏刷新加载
     */
    private fun dismissRefresh() {
        loadingTip.dismiss()
        if (smartRefresh.state.isOpening) {
            smartRefresh.finishLoadMore()
            smartRefresh.finishRefresh()
        }
    }
}